package com.data.algorithm.sort;

/**
 * 基数排序
 *
 * @author wangjie
 * @version V1.0
 * @date 2020/3/29
 */
public class RadixSort {

    public static void main(String[] args) {
        int[] arr = new int[800000];

        for (int i = 0; i < 800000; ++i) {
            arr[i] = (int) (Math.random() * 800000.0D);
        }

        Long startTime = System.currentTimeMillis();
        System.out.println("开始排序");
        radixSort(arr);
        Long endTime = System.currentTimeMillis() - startTime;

        System.out.println("排序耗时：" + endTime + "毫秒");
        System.out.println("排序耗时：" + endTime / 1000 + "秒");
    }

    /**
     * 基数排序
     * @param arr
     */
    public static void radixSort(int[] arr) {

        //1，找出数组中最大数的位数
        int max = arr[0];
        int maxLength;
        for(maxLength = 1; maxLength < arr.length; ++maxLength) {
            if (arr[maxLength] > max) {
                max = arr[maxLength];
            }
        }
        maxLength = String.valueOf(max).length();
        //2、定义一个二维数组，表示10个桶
        int[][] bucket = new int[10][arr.length];
        //3、定义一个一维数组，来记录每个桶里有几个数据
        int[] bucketElementCounts = new int[10];
        //4、循环
        for(int n = 1,i = 0; i < maxLength; i++,n *= 10) {

            for(int j = 0; j < arr.length; ++j) {
                int of = arr[j] / n % 10;
                bucket[of][bucketElementCounts[of]] = arr[j];
                ++bucketElementCounts[of];
            }

            for(int k = 0,index = 0; k < bucketElementCounts.length; ++k) {
                if (bucketElementCounts[k] != 0) {
                    for(int l = 0; l < bucketElementCounts[k]; ++l) {
                        arr[index++] = bucket[k][l];
                    }
                }
                bucketElementCounts[k] = 0;
            }
        }
    }
}
